package com.beidouapp.security.mvc;

import com.beidouapp.cache.impl.RedisDefaultAppCacheHelper;
import com.beidouapp.common.contant.SecurityContant;
import com.beidouapp.common.enums.YesNoEnum;
import com.beidouapp.domain.annotation.Right;
import com.beidouapp.domain.pojo.Organization;
import com.beidouapp.domain.pojo.OrganizationAndRole;
import com.beidouapp.domain.pojo.OrganizationExtend;
import com.beidouapp.exception.BusinessException;
import com.beidouapp.security.model.ReturnDataInfo;
import com.beidouapp.security.model.SessionUser;
import com.beidouapp.security.utils.DscpCommUtils;
import com.beidouapp.service.OrganizationService;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.util.*;

@Controller
@RequestMapping(value = "/organization")
public class OrganizationController {
    private static final Logger logger = LoggerFactory.getLogger(OrganizationController.class);

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private RedisDefaultAppCacheHelper redisCache;


    /**
     * 页面跳转
     *
     * @return
     */
    @Right(name={"org_manager"})
    @RequestMapping(value = "/page/list", method = RequestMethod.GET)
    public String forward2OrganizationPage() {
        return "organization/organization_list";
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @Right(name={"org_manager"})
    public
    @ResponseBody
    ReturnDataInfo<Organization> listOrganizations(HttpSession session, HttpServletRequest request, @RequestParam(value = "iDisplayStart", required = false, defaultValue = "0") Integer offset, @RequestParam(value = "iDisplayLength", required = false, defaultValue = "10") Integer limit, @RequestParam(value = "globalSearch", required = false, defaultValue = "{}") String globalSearch) {
        Map<String, Object> paramters = new HashMap<String, Object>();
        if (globalSearch != null) {
            JSONObject jsonObject = JSONObject.fromObject(globalSearch);
            paramters.putAll(jsonObject);
        }
        paramters.putAll(request.getParameterMap());
        try {
            if (DscpCommUtils.isSupperAdmin(session)) {
                //超级管理员.
                paramters.put("orgId", null);
            } else {
                SessionUser sessionUser = DscpCommUtils.getSessionUser(session);
                Long root_orgId = sessionUser.getOrgId();
                if (root_orgId == null) {
                    throw new Exception("您没有权限操作此项！");
                }
                paramters.put("orgId", root_orgId);
            }
            List<Organization> organizationList = organizationService.findOrganizationListWithPageByMap(offset, limit, paramters);
            Long total = organizationService.findOrganizationCountByMap(paramters);
            return ReturnDataInfo.createSuccessfulExecuteResults(organizationList, offset, limit, total);
        } catch (Exception ex) {
            logger.error("查询组织机构异常！", ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }

    /**
     * 添加页面跳转
     *
     * @return
     */
    @Right(name={"org_manager"})
    @RequestMapping(value = "/page/add", method = RequestMethod.GET)
    public String addOrganization() {
        return "organization/organization_add";
    }

    @Right(name={"org_manager"})
    @RequestMapping(value = "/add", method = RequestMethod.POST, headers = "Content-Type=application/json")
    public
    @ResponseBody
    ReturnDataInfo<String> addOrganization(HttpSession session, HttpServletRequest request, @RequestBody OrganizationExtend organizationExtend) {
        try {
            organizationExtend.setOrganizationTypeCode("h");
            organizationExtend.setCreateBy(DscpCommUtils.getSessionUser(session).getUserId());
            organizationExtend.setCreateTime(new Date());
            organizationService.insertOrganization(organizationExtend);
            return ReturnDataInfo.createSuccessfulSingleExecuteResult(null);
        } catch (Exception ex) {
            logger.error("添加机构异常！" + ex.getLocalizedMessage(), ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }

    /**
     * 编辑页面跳转
     *
     * @return
     */
    @Right(name={"org_manager","web_org_info"})
    @RequestMapping(value = "/page/edit/{orgId}", method = RequestMethod.GET)
    public ModelAndView modifyOrganization(HttpSession session, @PathVariable Long orgId) {
        ModelAndView view = new ModelAndView();
        view.addObject("orgId", orgId);
        view.setViewName("organization/organization_edit");
        return view;
    }

    @RequestMapping(value = "/get/{orgId}", method = RequestMethod.GET)
    public
    @ResponseBody
    ReturnDataInfo<Organization> getOrganizations(@PathVariable Long orgId) {
        if (orgId == null) {
            return ReturnDataInfo.createFailedExecuteResult("机构信息为空！");
        }
        try {
            Organization organization = organizationService.getOrganizationById(orgId);
            return ReturnDataInfo.createSuccessfulSingleExecuteResult(organization);
        } catch (Exception ex) {
            logger.error("获得机构异常！" + ex.getLocalizedMessage(), ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }


    @RequestMapping(value = "/listAll", method = RequestMethod.GET)
    public
    @ResponseBody
    ReturnDataInfo<Organization> findAllOrganizations() {
        Organization o = new Organization();
        o.setEnable("1");
        o.setIsDel(YesNoEnum.No.getCode());
        try {
            List<Organization> list = organizationService.findOrganizationList(o);
            return ReturnDataInfo.createSuccessfulExecuteResults(list);
        } catch (Exception ex) {
            logger.error("查询机构列表异常！" + ex.getLocalizedMessage(), ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }

    @Right(name={"org_manager"})
    @RequestMapping(value = "/delete", method = RequestMethod.POST, headers = "Content-Type=application/json")
    public
    @ResponseBody
    ReturnDataInfo<String> deleteOrganization(@RequestBody Map paramter) {
        try {
            String idsStr = (String) paramter.get("ids");
            String[] ids = idsStr.split(SecurityContant.SYMBOL_COMMA);
            List<Long> idList = new ArrayList<Long>(ids.length);
            for (String id : ids) {
                Long orgId = Long.valueOf(id);
                idList.add(orgId);
                List<OrganizationAndRole> list = organizationService.findOrganizationAndRoleList(orgId, null);
                if (!CollectionUtils.isEmpty(list)) {
                    throw new BusinessException("机构已分配，请先取消！");
                }
            }
            organizationService.removeOrganizationBatch(idList);
            return ReturnDataInfo.createSuccessfulSingleExecuteResult(null);
        } catch (Exception ex) {
            logger.error("删除机构异常！" + ex.getLocalizedMessage(), ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }

    @RequestMapping(value = "/province", method = {RequestMethod.POST, RequestMethod.GET})
    public
    @ResponseBody
    ReturnDataInfo<String> province(HttpSession session, HttpServletRequest request) {
        try {
            List<String> datas = (List<String>) redisCache.getCacheValue(SecurityContant.NAMESPACE, request.getParameter("code"));
            if(CollectionUtils.isEmpty(datas)){
                datas= Collections.emptyList();
            }
            return ReturnDataInfo.createSuccessfulExecuteResults(datas);
        } catch (Exception ex) {
            logger.error("地区信息获取异常！" + ex.getLocalizedMessage(), ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }

    @Right(name={"org_manager","web_org_info"})
    @RequestMapping(value = "/udpate", method = RequestMethod.POST, headers = "Content-Type=application/json")
    public
    @ResponseBody
    ReturnDataInfo<String> updateOrganization(HttpSession session, @RequestBody OrganizationExtend organization) {
        try {
            if (organization.getParentId() != null && organization.getId().longValue() == organization.getParentId().longValue()) {
                throw new Exception("所属组织机构配置不正确！");
            }
            organization.setOrganizationTypeCode("h");
            organizationService.modifyOrganization(organization);

            //TODO: 刷新驾校列表缓存数据
            //OrganizationExt organizationExt = ConvertUtils.convert(OrganizationExt.class, organization);
            //new Thread(new RefreshOrgSchoolToCache(organizationExt)).start();
            return ReturnDataInfo.createSuccessfulSingleExecuteResult(null);
        } catch (Exception ex) {
            logger.error("更新机构异常！" + ex.getLocalizedMessage(), ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }

    @Right(name={"org_manager"})
    @RequestMapping(value = "/page/grantRole/{orgId}", method = RequestMethod.GET)
    public ModelAndView grantOrganizationRole(@PathVariable Long orgId) {
        ModelAndView view = new ModelAndView();
        view.addObject("orgId", orgId);
        view.setViewName("organization/organization_role");
        return view;
    }


    @RequestMapping(value = "/page/detailinfo", method = RequestMethod.GET)
    public ModelAndView viewOrganizationInfoPage(HttpSession session) {
        ModelAndView view = new ModelAndView();
        view.addObject("orgId", DscpCommUtils.getSessionUser(session).getOrgId());
        view.setViewName("organization/organization_info");
        return view;
    }
    //--------------------------
}
